# coding=utf-8

from flask import current_app
import datetime
import inspect
import socket
from datetime import time


def job_task():
    current_app.logger.info("Job is working: %s" % (datetime.datetime.now()))
    m = Memory()
    data = m.runAllGet()
    current_app.logger.info(data)

    '''
    top_info = subprocess.Popen(["top", "-n", "1"], stdout=subprocess.PIPE)
    out, err = top_info.communicate()
    out_info = out.decode('unicode-escape')
    print(out_info)
    lines = out_info.split('\n')
    current_app.logger.info(lines)
    '''


class Memory(object):
    def __init__(self):
        self.data = {}

    @staticmethod
    def getTime():
        timeStr = str(int(time.time()) + 8 * 3600)
        current_app.logger.info("getTime: %s", timeStr)
        return timeStr

    @staticmethod
    def getHost():
        current_app.logger.info("getHost: %s", socket.gethostname())
        return socket.gethostname()

    @staticmethod
    def getLoadAvg():
        with open('/proc/loadavg') as load_open:
            a = load_open.read().split()[:3]
            current_app.logger.info("getLoadAvg: %s", socket.gethostname())
            return ','.join(a)

    @staticmethod
    def getMemTotal():
        with open('/proc/meminfo') as mem_open:
            a = int(mem_open.readline().split()[1])
            current_app.logger.info("getMemTotal: %s", socket.gethostname())
            return a / 1024

    @staticmethod
    def getMemUsage(noBufferCache=True):
        if noBufferCache:
            with open('/proc/meminfo') as mem_open:
                T = int(mem_open.readline().split()[1])
                F = int(mem_open.readline().split()[1])
                B = int(mem_open.readline().split()[1])
                C = int(mem_open.readline().split()[1])
                return (T - F - B - C) / 1024
        else:
            with open('/proc/meminfo') as mem_open:
                a = int(mem_open.readline().split()[1]) - int(mem_open.readline().split()[1])
                return a / 1024

    @staticmethod
    def getMemFree(noBufferCache=True):
        if noBufferCache:
            with open('/proc/meminfo') as mem_open:
                T = int(mem_open.readline().split()[1])
                F = int(mem_open.readline().split()[1])
                B = int(mem_open.readline().split()[1])
                C = int(mem_open.readline().split()[1])
                return (F + B + C) / 1024
        else:
            with open('/proc/meminfo') as mem_open:
                mem_open.readline()
                a = int(mem_open.readline().split()[1])
                return a / 1024

    def runAllGet(self):
        current_app.logger.info("This is runAllGet")
        # 自动获取mon类里的所有getXXX方法，用XXX作为key，getXXX()的返回值作为value，构造字典
        for fun in inspect.getmembers(self, predicate=inspect.ismethod):
            if fun[0][:3] == 'get':
                self.data[fun[0][3:]] = fun[1]()
        return self.data
